<?php
// +----------------------------------------------------------------------
// | OneKeyAdmin [ Believe that you can do better ]
// +----------------------------------------------------------------------
// | Copyright (c) 2020-2023 http://onekeyadmin.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: MUKE <513038996@qq.com>
// +----------------------------------------------------------------------
namespace plugins\weblogin\api\controller;

use onekey\File;
use app\api\BaseController;
use app\api\model\Config;
use app\api\model\UserGroup;
use plugins\weblogin\api\model\UserWechatlogin;
/**
 * 微信扫码登录
 */
class Wechat extends BaseController
{
    /**
     * 微信登录
     */
    public function login()
    {
        $config = Config::getVal('app_wechatlogin');
        if (isset($config['open']) && $config['open'] == 1) {
            $appid = $config['appid'];
            $uri = urlencode(index_url('weblogin/wechat/openid'));//重定向地址
            $url = "https://open.weixin.qq.com/connect/qrconnect?appid=$appid&redirect_uri=$uri&response_type=code&scope=snsapi_login&state=STATE#wechat_redirect";
            header("location:$url");
        }
    }

    /**
     * 获取用户信息
     */
    public function openid()
    {
        $config = Config::getVal('app_wechatlogin');
        $appid  = isset($config['appid']) ? $config['appid'] : '';
        $secret = isset($config['secret']) ? $config['secret'] : '';
        $code   = $_GET["code"];
        $oauth2Url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appid&secret=$secret&code=$code&grant_type=authorization_code";
        $oauth2 = curl($oauth2Url);
        $oauth2 = json_decode($oauth2,true);
        // 获得 access_token和openid
        $access_token = $oauth2["access_token"];
        $openid = $oauth2['openid'];
        $userId = UserWechatlogin::where('openid', $openid)->value('user_id');
        $userInfo = User::where('id', $userId)->find();
        if (! $userInfo) {
            $get_user_info_url = "https://api.weixin.qq.com/sns/userinfo?access_token=$access_token&openid=$openid&lang=zh_CN";
            $wechat_userinfo = curl($get_user_info_url);
            $wechat_userinfo = json_decode($wechat_userinfo,true);
            $cover = self::cover($wechat_userinfo['headimgurl']);
            $date  = date('Y-m-d H:i:s');
            $userInfo = User::create([
                'nickname'         => $wechat_userinfo['nickname'],
                'sex'              => $wechat_userinfo['sex'],
                'email'            => "",
                'mobile'           => "",
                'password'         => "",
                'cover'            => $cover,
                'describe'         => "这个人很懒，什么都没有留下。",
                'birthday'         => date('Y-m-d'),
                'now_integral'     => 0,
                'history_integral' => 0,
                'balance'          => 0,
                'pay_paasword'     => "",
                'login_ip'         => $this->request->ip(),
                'login_count'      => 1,
                'login_time'       => $date,
                'update_time'      => $date,
                'create_time'      => $date,
                'status'           => 1,
                'reason'           => '',
                'hide'             => 1,
            ]);
            UserWechatlogin::create([
                'openid'  => $wechat_userinfo['openid'],
                'user_id' => $userInfo->id,
            ]);
        } else {
            $userInfo->login_count = $userInfo->login_count + 1;
            $userInfo->login_ip    = request()->ip();
            $userInfo->login_time  = date('Y-m-d H:i:s');
            $userInfo->save();
        }
        // 生成令牌
        $token = password_hash($userInfo->id . $this->request->ip() . $openid, PASSWORD_BCRYPT, ['cost' => 12]);
        UserToken::create([
            'user_id'     => $userInfo->id,
            'token'       => $token,
            'create_time' => date('Y-m-d H:i:s')
        ]);
        $userInfo->group = UserGroup::where('integral', '<=', $userInfo->history_integral)->order('integral', 'desc')->find();
        $userInfo->token = $token;
        return json(['status' => 'success', 'message' => '登录成功', 'userInfo' => $userInfo]);
    }
    
    /**
     * 微信头像保存到本地
     */
    public static function cover($url) {
        if (! empty($url)) {
            $name     = md5((string) microtime(true));
            $type     = self::onlineType($url);
            $typeArr  = explode('/',$type);
            if ($typeArr[0] === 'image') {
                $suffix   = '.' . $typeArr[1];
                $path = public_path()."upload/user/" . date('Ymd') . "/";
                $fileName = $path . $name . $suffix;
                $content  = curl($url);
                $filePut  = File::create($fileName, $content);
                if ($filePut) {
                    $newUrl = str_replace(public_path(), '/', $fileName);
                    return $newUrl;
                }
            }
        }
    }
    
    /**
     * 获取远程文件后缀
     */
    public static function onlineType($url) {
        $url = parse_url($url);
        if ($fp = @fsockopen($url['host'], empty($url['port']) ? 80 : $url['port'], $error)) {
            fputs($fp, "GET " . (empty($url['path']) ? '/' : $url['path']) . " HTTP/1.1\r\n");
            fputs($fp, "Host: {$url['host']}\r\n\r\n");
            while (!feof($fp)) {
                $tmp = fgets($fp);
                if (trim($tmp) == '') {
                    break;
                } else if (preg_match('/Content-Type:(.*)/si', $tmp, $arr)) {
                    return trim((string)$arr[1]);
                }
            }
            return null;
        } else {
            return null;
        }
    }
}